import { qrLoginAPI } from '../../utils/api';

interface QRCodeResponse {
  session_id: string;
  qr_code: string;
  expires_in: number;
}

interface LoginStatus {
  status: 'pending' | 'scanned' | 'confirmed' | 'expired';
  user?: {
    id: number;
    username: string;
    nickname: string;
    role: string;
    is_verified: boolean;
    avatar?: string;
  };
  access_token?: string;
  refresh_token?: string | null;
  token_type?: string;
}

Page({
  data: {
    qrCode: '',
    sessionId: '',
    status: 'pending',
    countdown: 0,
    isGenerating: false,
    userInfo: null,
    pollInterval: null,
    countdownInterval: null
  },

  onLoad() {
    this.generateQRCode();
  },

  onUnload() {
    this.clearIntervals();
  },

  onHide() {
    this.clearIntervals();
  },

  onShow() {
    if (this.data.sessionId && this.data.status !== 'confirmed') {
      this.startPolling();
    }
  },

  // 生成二维码
  async generateQRCode() {
    this.setData({ isGenerating: true });
    
    try {
      const data = await qrLoginAPI.generateQRCode();
      
      this.setData({
        qrCode: data.qr_code,
        sessionId: data.session_id,
        status: 'pending',
        countdown: data.expires_in,
        userInfo: null
      });

      this.startPolling();
      this.startCountdown();
      
      wx.showToast({
        title: '二维码生成成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('生成二维码失败:', error);
      wx.showToast({
        title: '生成二维码失败',
        icon: 'error'
      });
    } finally {
      this.setData({ isGenerating: false });
    }
  },

  // 刷新二维码
  refreshQRCode() {
    this.clearIntervals();
    this.generateQRCode();
  },

  // 扫描二维码
  scanQRCode() {
    console.log('开始扫描二维码...');
    
    wx.scanCode({
      success: (res) => {

        console.log('扫码成功:', res);
        return false
        this.handleScanResult(res);
      },
      fail: (error) => {
        console.error('扫码失败:', error);
        wx.showToast({
          title: '扫码失败',
          icon: 'error'
        });
      }
    });
  },

  // 处理扫码结果
  handleScanResult(scanResult: any) {
    try {
      console.log('处理扫码结果:', scanResult);
      
      // 解析扫码数据
      const scanData = this.parseScanData(scanResult.result);
      
      // 保存扫码数据到缓存
      wx.setStorageSync('scanData', {
        sessionId: scanData.sessionId,
        qrCode: scanResult.result,
        scanTime: new Date().toLocaleString(),
        deviceInfo: this.getDeviceInfo(),
        userInfo: this.data.userInfo
      });

      // 跳转到确认页面
      wx.navigateTo({
        url: '/pages/qrconfirm/qrconfirm'
      });

    } catch (error) {
      console.error('处理扫码结果失败:', error);
      wx.showToast({
        title: '二维码格式错误',
        icon: 'error'
      });
    }
  },

  // 解析扫码数据
  parseScanData(qrCodeData: string) {
    console.log('解析二维码数据:', qrCodeData);
    
    // 尝试解析JSON格式
    try {
      const data = JSON.parse(qrCodeData);
      return {
        sessionId: data.session_id || data.sessionId || 'unknown',
        type: data.type || 'login'
      };
    } catch (e) {
      // 如果不是JSON，尝试解析URL参数
      const params = {};
      const pairs = qrCodeData.split('&');
      for (let i = 0; i < pairs.length; i++) {
        const pair = pairs[i].split('=');
        if (pair.length === 2) {
          params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
      }
      return {
        sessionId: params['session_id'] || params['sessionId'] || 'unknown',
        type: params['type'] || 'login'
      };
    }
  },

  // 获取设备信息
  getDeviceInfo() {
    const systemInfo = wx.getSystemInfoSync();
    return `${systemInfo.platform} ${systemInfo.system} ${systemInfo.version}`;
  },

  // 开始轮询登录状态
  startPolling() {
    if (this.data.pollInterval) {
      clearInterval(this.data.pollInterval);
    }

    const pollInterval = setInterval(async () => {
      await this.checkLoginStatus();
    }, 2000);

    this.setData({ pollInterval });
  },

  // 检查登录状态
  async checkLoginStatus() {
    if (!this.data.sessionId) return;

    try {
      const status = await qrLoginAPI.checkLoginStatus(this.data.sessionId);
      
      this.setData({
        status: status.status
      });

      switch (status.status) {
        case 'scanned':
          wx.showToast({
            title: '已扫码，请确认登录',
            icon: 'none'
          });
          break;

        case 'confirmed':
          this.handleLoginSuccess(status);
          break;

        case 'expired':
          this.handleQRExpired();
          break;
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
    }
  },

  // 处理登录成功
  handleLoginSuccess(loginData: LoginStatus) {
    this.clearIntervals();
    
    // 保存用户信息和token
    wx.setStorageSync('userInfo', loginData.user);
    wx.setStorageSync('accessToken', loginData.access_token);
    wx.setStorageSync('tokenType', loginData.token_type);
    
    this.setData({
      userInfo: loginData.user,
      status: 'confirmed'
    });

    wx.showToast({
      title: '登录成功！',
      icon: 'success'
    });

    // 准备用户信息数据
    const userInfoData = {
      nickname: (loginData.user && loginData.user.nickname) || '魔力玩家',
      avatar: (loginData.user && loginData.user.avatar) || '/static/default-avatar.png',
      level: '1',
      gameId: (loginData.user && loginData.user.username) || 'Player001',
      qq: '未设置',
      registerTime: new Date().getFullYear() + '年'
    };

    // 延迟跳转到登录成功页面
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login-success/login-success?userInfo=' + encodeURIComponent(JSON.stringify(userInfoData)),
        success: () => {
          console.log('跳转到登录成功页面');
        },
        fail: (error) => {
          console.error('跳转到登录成功页面失败:', error);
          // 如果跳转失败，回退到首页
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      });
    }, 1500);
  },

  // 处理二维码过期
  handleQRExpired() {
    this.clearIntervals();
    
    this.setData({
      status: 'expired',
      countdown: 0
    });

    wx.showToast({
      title: '二维码已过期',
      icon: 'error'
    });
  },

  // 开始倒计时
  startCountdown() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
    }

    const countdownInterval = setInterval(() => {
      if (this.data.countdown > 0) {
        this.setData({
          countdown: this.data.countdown - 1
        });
      } else {
        this.handleQRExpired();
      }
    }, 1000);

    this.setData({ countdownInterval });
  },

  // 清除所有定时器
  clearIntervals() {
    if (this.data.pollInterval) {
      clearInterval(this.data.pollInterval);
      this.setData({ pollInterval: null });
    }
    
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: '扫码登录 - 快速安全的登录方式',
      path: '/pages/qrlogin/qrlogin'
    };
  }
}); 